
import React, { useState, useRef, useEffect } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Row, Col, Space, Button } from 'antd';
import { useModel } from 'umi'; 
import { PageContainer } from '@ant-design/pro-layout';
import { updateOrResetPwd, getOperList } from '@/services/permissions/api';
import ProForm, { ProFormText, ModalForm } from '@ant-design/pro-form';
import { OptType } from '@/utils/constants';
import { isNull, MsgType, showMsg } from '@/utils/utils';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import sha1 from "@/utils/SHA1"; // 密码转义

const RoleList: React.FC = () => {

  const { initialState } = useModel('@@initialState');
  const formRef = useRef();
  const formRef1 = useRef();
  const [visible, setVisible] = useState(false);
  const [curOper, setCurOper] = useState({});

  const changePwd = async(values, oper_type) => {
    console.log(values);
    if (oper_type === 'N' && isNull(curOper.staff_code)) {
      showMsg('请输入工号');
      return;
    }
    console.log('sha1', sha1)
    const params = {
      oper_type,
      staff_code: oper_type === 'R' ? initialState?.currentUser?.oper_id : curOper.staff_code,
      login_pwd: values.login_pwd ? sha1.hex_sha1(values.login_pwd) : '',
      new_pwd: values.new_pwd ? sha1.hex_sha1(values.new_pwd) : '',
      old_pwd: values.old_pwd ? sha1.hex_sha1(values.old_pwd) : '',
    };
    console.log('params', params);
    await updateOrResetPwd(params).then(res => {
      if (oper_type === 'R') {
        setVisible(false);
        showMsg('已重置密码', 'success');
        formRef?.current?.resetFields();
      } else {
        showMsg('已保存，请重新登录', 'success');
        localStorage.clear();
        window.location.replace('http://10.101.1.150:8108/portal/');
      }
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    })
  }

  const check = (value, callback) => {
    console.log('check-value', value)
    const reg = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,15}$/);
    if (reg.test(value)) {
      console.log('success')
      // callback();
    } else {
      // Promise.reject(new Error('')); 
      console.log('error')
      throw new Error('超管密码为8-15位大写字母+小写字母+数字组合!');
    }
  }
  
  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
       <div style={{ background: '#fff', paddingTop: '8%', height: window.innerHeight - 55, }}>
        <ProForm
          formRef={formRef}
          style={{ background: '#fff', padding: '20px 0', border: '1px #ddd solid', width: 600, margin: '0 auto' }}
          title="切换账号"
          layout='horizontal'
          submitter={{
            render: (props, doms) => {
              return <Row gutter={24}>
              <Col span={12} offset={9}>
                <Space>
                  <Button type='primary' onClick={() => formRef.current.submit()}>确认修改</Button>
                  <Button type='primary' onClick={() => setVisible(true)}>重置密码</Button>
                </Space>
              </Col>
            </Row>
            },
            
          }}
          labelCol={{ span: 8 }}
          modalProps={{
            onCancel: () => setVisible(false),
            maskClosable: false
          }}
          onFinish={async (values) => {
            await changePwd(values, 'N');
          }}
        >
          <ProFormText
            width="md"
            name="dest_oper_id"
            label="工号"
            placeholder="请输入工号"
            initialValue={initialState?.currentUser?.staff_code}
            rules={[
              {
                required: true,
              },
            ]}
            fieldProps={{
              onBlur: async(e) => {
                console.log('onblur', e.target.value, formRef.current)
                if (isNull(e.target.value)) {
                  return;
                }
                await getOperList({ staff_code: e.target.value }).then(res => {
                  if (isNull(res.record_list)) {
                    showMsg('未查到相关信息，请重新输入');
                    formRef?.current?.setFieldsValue({ dest_oper_id: null });
                    return;
                  }
                  const result = res.record_list[0];
                  setCurOper(result);
                  formRef?.current?.setFieldsValue({ oper_name: result.staff_name, dept_name: result.admin_dept_name })
                }).catch((error) => {
                  showMsg(error?.data?.errmsg)
                })
              }
            }}
          />
          <ProFormText
            width="md"
            label="姓名"
            name='oper_name'
            readonly
            initialValue={initialState?.currentUser?.oper_name}
          />
          <ProFormText
            width="md"
            label="归属科室"
            name='dept_name'
            readonly
            initialValue={initialState?.currentUser?.dept_name}
          />
          <ProFormText.Password
            width="md"
            name="login_pwd"
            label="超管密码"
            placeholder="请输入超管密码"
            fieldProps={{
              autoComplete: 'new-password',
            }}
            rules={[
              {
                required: true,
              },
            ]}
          />

        </ProForm>
      </div>
      {
        visible &&
        <ModalForm
          title="重置密码"
          formRef={formRef1}
          visible
          style={{ width: '600px' }}
          layout='horizontal'
          submitter={{
            searchConfig: {
              submitText: '确认',
              resetText: '取消',
            },
          }}
          labelCol={{ span: 8 }}
          modalProps={{
            onCancel: () => setVisible(false),
            maskClosable: false
          }}
          onFinish={async (values) => {
            // await waitTime(2000);
            console.log('values', values);
            if (values.new_pwd !== values.new_pwd1) {
              showMsg('二次确认密码与新密码不一致，请修改');
              return;
            }
            await changePwd(values, 'R');
          }}
        >
          <ProFormText.Password
            width="md"
            name="old_pwd"
            label="原密码"
            placeholder="请输入原密码"
            fieldProps={{
              autoComplete: 'new-password',
              maxLength: 15,
            }}
            rules={[
              {
                required: true,
              },
            ]}
          />
          <ProFormText.Password
            width="md"
            name="new_pwd"
            label="新密码"
            placeholder="请输入新密码"
            fieldProps={{
              autoComplete: 'new-password',
              maxLength: 15,
            }}
            rules={[
              {
                required: true,
              },
              {
                validator: async (rule, value) => {
                  if (value === formRef1.current.getFieldValue('old_pwd')) {
                    throw new Error('原密码不能与新密码相同!');
                  }
                  check(value);
                }
              }
            ]}
          />
          <ProFormText.Password
            width="md"
            name="new_pwd1"
            label="二次确认新密码"
            placeholder="请输入二次确认新密码"
            fieldProps={{
              autoComplete: 'new-password',
              maxLength: 15,
            }}
            
            rules={[
              {
                required: true,
              },
              {
                validator: async(e, val, callback) => {
                  console.log('val', val, formRef1.current.getFieldValue('new_pwd'))
                  if (val !== formRef1.current.getFieldValue('new_pwd')) {
                    throw new Error('二次确认密码与新密码不一致');
                  } else {
                    callback();
                  }
                  
                }
              }
            ]}
          />
          <div className="org" style={{ marginLeft: '33%' }}>
            <ExclamationCircleOutlined style={{ marginRight: 5 }} />
            超管密码为8-15位大写字母+小写字母+数字组合
          </div>
        </ModalForm>
      }
    </PageContainer>
  );
};

export default RoleList;
